package org.fast.develop.logicflow.runtime.convert.execute;

import cn.hutool.json.JSONObject;
import org.fast.develop.logicflow.core.meta.builder.ElementFactory;
import org.fast.develop.logicflow.core.meta.shape.LogicFlowDefinition;
import org.fast.develop.logicflow.runtime.convert.builder.DesignerModelBuilder;

import java.util.ArrayList;
import java.util.List;

/**
 * @author czh
 * @version V1.0
 * @data Created on 2023-01-03 10:11
 */
public class DefinitionsToJsonExecutor {

    private ElementFactory elementFactory;

    private DesignerBuilderFactory designerBuilderFactory;

    public DefinitionsToJsonExecutor(ElementFactory elementFactory, DesignerBuilderFactory designerBuilderFactory) {
        this.elementFactory = elementFactory;
        this.designerBuilderFactory = designerBuilderFactory;
    }

    /**
     * 从logicFlowDefinition转json
     *
     * @param logicFlowDefinition
     * @return
     */
    public String execute(LogicFlowDefinition logicFlowDefinition) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("id", logicFlowDefinition.getResourceId());
        jsonObject.set("author", logicFlowDefinition.getAuthor());
        jsonObject.set("version", logicFlowDefinition.getVersion());
        jsonObject.set("name", "");
        List<JSONObject> definitions = new ArrayList<>();
        logicFlowDefinition.getDefinitions().getList().forEach(item -> {
            String type = elementFactory.getType(item.getClass());
            DesignerModelBuilder designerModelBuilder = designerBuilderFactory.create(type);
            designerModelBuilder.convert(definitions, item);
        });
        jsonObject.set("definitions", definitions);
        return jsonObject.toJSONString(0);
    }
}
